<template>
	<Layout>
		<div v-show="!progressShow">
			<Form ref="form1" :model="dataToQuery" :label-width="90">
				<Row class="query-form">
					<Col span="8">
					<FormItem label="二级集团：" prop="belongOrgId">
						<Select class='query-form-el' v-model='dataToQuery.belongOrgId' clearable>
							<Option v-for="item in dicMap.twoLevel" :value="item.orgId" :key="item.orgId">
								{{item.orgName}}</Option>
						</Select>
					</FormItem>
					</Col>
					<Col span="8">
					<FormItem label="年度：" prop="year1">
						<DatePicker class="query-form-el" type="year" placeholder="请选择年度" v-model="dataToQuery.year1"
							:clearable="false"
							@on-change="()=>{if(dataToQuery.year1 instanceof Date){dataToQuery.year = dataToQuery.year1.getFullYear().toString()}}">
						</DatePicker>
					</FormItem>
					</Col>
					<!-- <Col span="5">
                        <FormItem label="任务书类型：" prop="assessmentType" :label-width="100">
                            <Select v-model='dataToQuery.assessmentType' :clearable="false" class="query-form-el" placeholder="请选择任务书类型" @on-change="query">
                                <Option v-for="item in dicMap.assessmentTypes" :value="item.code" :key="item.code">{{item.name }}
                                </Option>
                            </Select>
                        </FormItem>
                    </Col> -->
					<Col span="8" v-if="!switchFlag">
					<!--<Button @click="switchQuery(true)" class="ivu-btn-switch" type="text">展开∨</Button>-->
					<Button @click="reset1" class="ivu-btn-reset">重置</Button>
					<Button class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
					</Col>
				</Row>

			</Form>
			<Row :gutter="24" style="margin-top: 15px">
				<Col span="12">
				<Card dis-hover>
					<div ref="echart1" :style="{height: '250px'}"></div>
				</Card>
				</Col>
				<Col span="12">
				<Card dis-hover>
					<div ref="echart2" :style="{height: '250px'}"></div>
				</Card>
				</Col>
			</Row>
			<Row :gutter="24" style="margin-top: 15px">
				<Col span="24">
				<Row class="query-form">
					<Col span="20" style="margin-top: 10px;margin-left: 10px">
					<p>扣分最多10个公司</p>
					</Col>
					<!-- <Col span="2">
                            <Button type="primary" :disabled="dataTable.length<1" class="ivu-btn-add" icon="md-cloud-download" @click="exportForm('1')">导出</Button>
                        </Col> -->
				</Row>
				<Table ref='table' :height="tableHeight" no-data-text="没有查询到相关数据!" :loading='pageStatus.loading' border
					:columns="columns1" :data="dataTable">
				</Table>
				<!-- <Row style="margin-right:10px;">
                        <Col span="24">
                            <Page style="float: right" :total="pagedata.total" :page-size="pagedata.pageSize" @on-change="pageChange"
                                  @on-page-size-change="pageSizeChange" :page-size-opts="pageSizeArray" show-total show-sizer
                                  show-elevator/>
                        </Col>
                    </Row> -->
				</Col>
				<!-- <Col span="12">
                    <Row class="query-form">
                        <Col span="20" style="margin-top: 10px;margin-left: 10px"> <p>二级集团任务书完成情况</p></Col>
                        <Col span="2">
                            <Button type="primary" :disabled="twoLevelData.length<1" class="ivu-btn-add" icon="md-cloud-download" @click="exportForm('0')">导出</Button>
                        </Col>
                    </Row>
                    <Table ref='table' :height="tableHeight" no-data-text="没有查询到相关数据!"
                           :loading='pageStatus.loading' border :columns="columns2" :data="twoLevelData">
                    </Table>
                </Col> -->
			</Row>
		</div>

		<task-book-progress v-if="progressShow" :show="progressShow" :taskBook="dataToView" :view="true"
			@close="progressShow = false" />
	</Layout>
</template>

<script>
	import echarts from "echarts";
	import {
		Api
	} from '@/api/index.js'
	import pageCommonFunction from '@/components/pageCommonFunction.js'
	import {
		sessionStorage
	} from '@/common/cacheUtils.js';
	import taskBookProgress from './taskBookProgress'
	var cascaderDom = () => import('@/components/cascader-dom.vue');

	export default {
		components: {
			cascaderDom,
			taskBookProgress
		},
		computed: {
			isResult() {
				return this.$route.name
			}
		},
		data() {
			return {
				...this.createCommonDataField(),
				companyId: sessionStorage('userId').getObject('userId').companyId,
				columns1: [{
						title: '序号',
						width: 65,
						align: 'center',
						render: this.indexColumnsRender
					},
					{
						minWidth: 150,
						title: '单位名称',
						align: 'center',
						key: 'companyName',
						tooltip: true
					},
					{
						minWidth: 150,
						title: '二级集团',
						align: 'center',
						key: 'belongOrgName',
						tooltip: true
					},
					{
						key: 'progress',
						title: '扣分',
						align: 'center',
						width: 80,
					},
					{ key:'scoreDesc',title: '扣分描述',  align: 'center', minWidth: 200,tooltip:true},
					{
						title: '操作',
						key: 'action',
						// fixed: 'right',
						width: 100,
						align: 'center',
						render: (h, params) => {
							return h('div', [
								h('A', {
									props: {
										type: 'primary',
										size: 'small'
									},
									style: {
										fontSize: '14px',
									},
									on: {
										click: () => {
											this.progressShow = true
											this.dataToView = {
												...params.row
											}
										}
									}
								}, '进展详情'),
							])
						}
					}
				],
				// twoLevelData:[],
				// columns2: [
				//     {title: '序号', width: 65, align: 'center', render: this.indexColumnsRender},
				//     {minWidth: 200, title: '二级集团', align: 'center', key: 'belongOrgName',tooltip:true},
				//     { key:'progress',title: '完成进度',  align: 'center', width: 90,   render: (h, params) => {
				//             return h('span', params.row.progress? params.row.progress+'%':'');}},
				//     {
				//         title: '操作',
				//         key: 'action',
				//         // fixed: 'right',
				//         width: 70,
				//         align: 'center',
				//         render: (h, params) => {
				//             return h('div', [
				//                 h('A', {
				//                     props: {type: 'primary', size: 'small'},
				//                     style: {
				//                         fontSize: '14px',
				//                         color: params.row.type == 0 ? '#d0d0d0' : '',
				//                         pointerEvents: params.row.type == 0 ? 'none' : ''
				//                     },
				//                     on: {
				//                         click: () => {
				//                             this.progressShow = true
				//                             this.dataToView = {...params.row}
				//                         }
				//                     }
				//                 }, '详情'),
				//             ])
				//         }
				//     }
				// ],
				progressShow: false,

				dicMap: {
					twoLevel: [],
					assessmentTypes: [{
						code: '1',
						name: '安全'
					}, {
						code: '2',
						name: '环保'
					}],
				},
				tableHeight: 10,
				// api
				queryUrl: Api.queryTaskBook + '/statistics',
				exportUrl: Api.queryTaskBook + '/statistics/export',

				currentUser: JSON.parse(sessionStorage('userId').get('userId')),
			}
		},
		mounted() {
			// this.setTableHeight();
			this.dataToQuery.year1 = new Date()
			this.dataToQuery.year = new Date().getFullYear().toString()
			// this.dataToQuery.assessmentType = '1'
			this.tableHeight = 300
			this.$http.get(Api.quqeryTwoOrgInfo).then(res => {
				this.dicMap.twoLevel = res.data.data
			})
			this.query();
		},
		methods: {
			...pageCommonFunction,

			exportForm(type) {
				this.dataToQuery.type = type
				this.exportFormSubmit()
			},
			reset1() {
				this.dataToQuery = {
					// assessmentType: '1',
					year1: new Date(),
					year: new Date().getFullYear().toString()
				}
				this.query()
			},
			query() {
				this.dataToQuery.assessmentType = this.isResult == 'taskBookStatistics' ? '2' : '1'
				this.queryAjax();
			},
			queryAjax() {
				this.pageStatus.loading = true
				let data = {
					startPage: this.pagedata.currentPage,
					size: this.pagedata.pageSize,
					conditions: this.dataToQuery
				};
				let container1 = echarts.init(this.$refs.echart1);
				let container2 = echarts.init(this.$refs.echart2);

				this.$http.post(this.queryUrl, data).then((res) => {
					if (res.data.status === 201) {
						this.$Message.error(res.data.msg);
					}
					if (res.data.status === 200) {
						this.dataTable = res.data.data.data;
						this.pagedata.total = res.data.data.totalSize;
						// this.twoLevelData = res.data.data.twoLevelData;
						this.pageStatus.loading = false
						this.dataMap = res.data.data.dataMap;
						let option1 = this.getOption(this.dataMap.twoLevel, this.dataMap.twoLevelNum, {
							type: 'value',
							minInterval: 1
						}, '任务书签订数量');
						container1.setOption(option1);
						window.onresize = container1.resize;

						let map = {
							type: 'value',
							min: 0,
							max: 100,
							minInterval: 1,
							axisLabel: {
								formatter: '{value} %'
							}
						}
						let option2 = this.getPieOption(this.dataMap.pieScore, '扣分入口统计');
						container2.setOption(option2);
						window.onresize = container2.resize;
					}
				}).catch(e => {
					this.$Message.error("数据获取失败")
					this.pageStatus.loading = false
				})
			},

			getOption(xData, yData, yMap, titleName) {
				return {
					title: {
						text: titleName,
						textStyle: {
							fontSize: 14,
						},
						left: 'center'
					},
					tooltip: {
						trigger: 'axis',
						axisPointer: {
							type: 'shadow'
						}
					},
					// grid: {
					//     left: '1%',
					//     right: '1%',
					//     bottom: '1%',
					//     containLabel: true,
					// },
					// legend: {
					//     data: ['正在作业']
					// },
					// toolbox: {
					//     show: true,
					//     orient: 'vertical',
					//     left: 'right',
					//     top: 'center',
					// },
					xAxis: [{
						type: 'category',
						// axisTick: {show: false},
						data: xData,
						axisLabel: {
							show: true,
							interval: 0,
							rotate: -25,
							fontSize: 12,
						},
					}],
					yAxis: [
						yMap
					],
					color: ['#42A5F5'],
					series: [{
						name: titleName,
						type: 'bar',
						// barWidth : 30,
						barGap: "1%",
						label: {
							show: true,
						},
						itemStyle: {
							barBorderRadius: [4, 4, 0, 0],
						},
						data: yData,
					}]
				}
			},
			getPieOption(data, titleName, seriesRadius) {
				return {
					title: {
						text: titleName,
						textStyle: {
							fontSize: 14,
						},
						left: 'center'
					},
					tooltip: {
						show: true,
					},
					legend: {
						icon: "circle",
						orient: 'vertical',
						right: '15%',
						// top:'7%',
						y: "center",
						type: 'scroll',
						itemHeight: 18,
						tooltip: {
							show: true
						},
						formatter: function(name) {
							let total = 0;
							let target;
							for (let i = 0; i < data.length; i++) {
								total += data[i].value;
								if (data[i].name == name) {
									target = data[i].value;
								}
							}
							if (!target) {
								target = 0;
							}
							let percentage = 0
							if (total) {

								percentage = ((target / total) * 100).toFixed(2) + '%';
							}

							return name + '  ' + target ;
						},
					},
					color: ['#42A5F5', '#4CD1A8', '#FFC310', '#FD5C50'],
					series: [{
						// name: titleName,
						type: 'pie',
						// radius: ['40%', '70%'],
						...seriesRadius,
						center: ["25%", "50%"],
						avoidLabelOverlap: false,
						itemStyle: {
							borderRadius: 10,
							borderColor: '#fff',
							borderWidth: 8,
						},
						label: {
							show: false,
							position: 'center'
						},
						emphasis: {
							label: {
								show: false,
							}
						},
						labelLine: {
							show: false
						},
						data: data
					}]
				};
			},
		},
		watch: {
			'dataTable': function() {
				// this.dataTable.forEach(m=>{
				//     if (m.briefId === '-1') {
				//         m['_disableExpand'] = true
				//     }
				// })
			}
		},
	}
</script>

<style lang='css' scoped>
	.ivu-form-item {
		padding-right: 20px;
	}

	.query-form-el,
	.ivu-date-picker,
	.ivu-input-wrapper {
		width: 100%;
	}

	p {
		display: inline-block;
		font-size: 18px;
	}
</style>
